gpt4 book ai didi

java - RESTful 服务调用

转载 作者:行者123 更新时间:2023-11-30 03:48:21 26 4
gpt4 key购买 nike

我正在使用 Chrome 插件,并且可以成功让我的服务正常工作:

enter image description here

我现在正尝试将同样的事情放入我的 Java 调用中。不过,我在将 Raw 部分放入我的 Java 服务时遇到问题。有什么想法吗?

  httpPost = new HttpPost(URL);
nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("Authorization", "Bearer " + token));
nvps.add(new BasicNameValuePair("Content-Type", "application/json"));

//I know this part is incorrect, but I don't know what to do with it
nvps.add(new BasicNameValuePair("{\"pCode\": \"\", \"rType\": \"Sales Case\", \"subject\": \"test3\", \"description\": \"test4\", \"lookupInfo\": \"test5\", \"aaNum\": \"\"}", ""));

try
{
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}

HttpResponse response;
try {
response = client.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String builder = "";

String line = in.readLine();
System.out.println("line = " + line);
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}

最佳答案

HttpClient

我不知道你用什么来进行http调用,但是为了简单和理智,使用apache的httpclient。

示例

    HttpPost post = new HttpPost(URL);

post.setHeader("Content-type", "application/json");
post.setHeader("Authorization", "Bearer " + token));
post.setHeader("Cache-Control", "no-cache"));

FileBody fileBody = new FileBody(file);
StringBody pCode = new StringBody("SOME TYPE OF VALUE", ContentType.MULTIPART_FORM_DATA);
StringBody rType = new StringBody("SOME TYPE OF VALUE", ContentType.MULTIPART_FORM_DATA);
//
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("pCode", pCode);
builder.addPart("rType", rType);
HttpEntity entity = builder.build();
try
{
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
}catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}

HttpResponse response;
try {
response = client.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String builder = "";

String line = in.readLine();
System.out.println("line = " + line);
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}

}

此代码尚未经过测试。

更新

JSON 只是一个奇特的字符串(从 java 的角度来看),所以只需添加以下内容:

builder.addPart("someName", new StringBody(json, ContentType.TEXT_PLAIN));

更新2

上面将 JSON 添加为 POST 变量,而不是正文。 Look AT This Post

关于java - RESTful 服务调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25024335/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com