对WEB url 发送POST请求

package com.excellence.spark;

import java.util.List;
import com.excellence.spark.test.test;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.Import;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.net.URLDecoder;
 
/**    对指定url发送post的指定内容
 * @author 947
 *
 */
public class HttpRequest {
    /**
     * 
     * @param url         url
     * @param content      发送post的内容
     * @return
     */
    public static String httpPost(String url,String content){
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = new JSONObject();
      
        HttpPost method = new HttpPost(url);
        try {
            if (null != content) {
                StringEntity entity = new StringEntity(content, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);

            url = URLDecoder.decode(url, "UTF-8");
  
            String entity = EntityUtils.toString(result.getEntity());    // 拿到响应的实体的字符串
            
            System.out.println(entity);
            return entity;
            
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static void main(String[] args) {
        String url = "http://127.0.0.1:8000/index/";
        JSONObject jsonObject =  new JSONObject();
        jsonObject.put("word", "111111");
        String result = HttpRequest.httpPost(url, jsonObject.toString());  // 返回响应结果
        System.out.println(result);
    }
}

如何在python中拿到这个request然后并响应返回response呢???

#-*-coding:utf-8-*-

from importlib import reload
import json
from django.shortcuts import render
from django.shortcuts import HttpResponse
import requests
from sendPostText.predict import CnnModel

def index(request):
    cnn_model = CnnModel()

    received_json_data = json.loads(request.body)
    word = received_json_data['word']

    result = cnn_model.predict(word)

    data = {'word':result}

    data = json.dumps(data,ensure_ascii=False)  # 这里加入ensure_ascil=False保证中文不乱码
    response = HttpResponse(data,content_type="application/json,charset=UTF-8")
    return response

 

转载于:https://www.cnblogs.com/yiduobaozhiblog1/p/9945039.html

你可能感兴趣的:(对WEB url 发送POST请求)