java执行post请求,并获取json结果组成想要的内容存放本地txt中

大概就是这样一个post

然后用户的需求是:

1、分析这个接口,实现
1.1 获取到sentence,  score字段值
1.2 这个score值如果是<0.5,打印分值 情感倾向:0
      这个score值如果是>=0.5,打印分值 情感倾向:1

输出文本中的结果为:

这里用到了httpclient,要用到的jar包,下载的gz包解压把lib里的jar包build到eclipse项目中去(此步省)

链接:https://pan.baidu.com/s/1DXp2GLwLg7cNOzKviqAeBw
提取码:odf6
链接:https://pan.baidu.com/s/1YodlzLMQ8RcWbCniJrvxPA
提取码:lxa3

直接上代码吧,都是我拼凑起来的:

package desi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import net.sf.json.JSONObject;

public class PostURL {
	/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
	public static List<String> readFile02(String path)  {
        // 使用一个字符串集合来存储文本中的路径 ,也可用String []数组
        List<String> list = new ArrayList<String>();
        try {
			FileInputStream fis = new FileInputStream(path);
			// 防止路径乱码   如果utf-8 乱码  改GBK     eclipse里创建的txt  用UTF-8,在电脑上自己创建的txt  用GBK
			InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			String line = "";
			while ((line = br.readLine()) != null) {
				// 如果 t x t文件里的路径 不包含---字符串       这里是对里面的内容进行一个筛选
				list.add(line);
			}
			br.close();
			isr.close();
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
        return list;
    }
	//把字符串一行行写入文件
	public static void writeTxt(String result,String resultfilepath) {
		//写入中文字符时解决中文乱码问题
        try {
			FileOutputStream fos = new FileOutputStream(new File(resultfilepath),true);
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
			BufferedWriter bw = new BufferedWriter(osw);
				bw.write(result + "\t\n");
			

			//注意关闭的先后顺序,先打开的后关闭,后打开的先关闭
			bw.close();
			osw.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//post请求获取结果
	/**
	*  sendUrl    (远程请求的URL)
	*  param    (远程请求参数)
	*  JSONObject    (远程请求返回的JSON)
	*/

	private static String sendPostUrl(String url, String param){
        PrintWriter out = null;
        BufferedReader in = null;
        JSONObject jsonObject = null;
        String result = "";
        List<String> reslutlist=new ArrayList<String>();
        String qingganqingxiang="";
        String jieguo="";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流(设置请求编码为UTF-8)
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 获取请求返回数据(设置返回数据编码为UTF-8)
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = JSONObject.fromObject(result);
            System.out.println(jsonObject);
            //分析结果,得出字符串 装了好几台机子了,一直都用这个===情感倾向:2===分值:0.632563
            if((Double.parseDouble(jsonObject.get("score").toString()))>=0.5){
            	qingganqingxiang="===情感倾向:2";
            }else {
            	qingganqingxiang="===情感倾向:0";
            }
           String score="===分值:"+jsonObject.get("score").toString();
           String sentence=jsonObject.get("sentence").toString();
           jieguo=sentence+qingganqingxiang+score;
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        
        return jieguo;
    }
  
    public static void main(String[] args) {
    	String httpposturl="http://47.107.235.26:8383/pconline-bds-emotion/api/v1.0/emoa";
    	String result_path="E:\\360downloads\\pos_result.txt";
    	List<String> sList=readFile02("E:\\360downloads\\pos.txt");
    	for (String param : sList) {
    		String res = sendPostUrl(httpposturl,"sentence="+param);
        	System.out.println(res);
        	writeTxt(res,result_path);
		}

	}
    
}

猜你喜欢

转载自www.cnblogs.com/sincoolvip/p/10310983.html