使用Apache HttpClient 4.5在big5中发送post请求编码。 Java代码如下,结果显示不可读的代码如???。 请提出一些建议来解决它。
hpr803.getResps1("http://web-reg-server.803.org.tw/TRE/stepB1.asp");
//the method to send post request and get response
public void getResps1(String param) throws IOException{
ArrayList<NameValuePair> pairList = new ArrayList<NameValuePair>();
// Post request example hospital 803
pairList.add(new BasicNameValuePair("syear", "104"));
pairList.add(new BasicNameValuePair("smonth", "7"));
pairList.add(new BasicNameValuePair("sday", "20"));
pairList.add(new BasicNameValuePair("eyear", "104"));
pairList.add(new BasicNameValuePair("emonth", "8"));
pairList.add(new BasicNameValuePair("eday", "5"));
pairList.add(new BasicNameValuePair("HospNO", "1"));
pairList.add(new BasicNameValuePair("SectNO", ""));
pairList.add(new BasicNameValuePair("EmpNO", ""));
HttpPost httpPost = new HttpPost(param);
//big5 code
StringEntity entity = new StringEntity(URLEncodedUtils.format(pairList, "big5"));
httpPost.setEntity(entity);
//httpPost.setEntity(new UrlEncodedFormEntity(pairList, "big5"));
CloseableHttpClient demo = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(param);
HttpResponse response = demo.execute(httpGet);
String responseString = EntityUtils.toString(response.getEntity(), "big5");
response = demo.execute(httpPost);
responseString = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("responseString big5 ~~~~~~~~~~ " +responseString);
} else {
System.out.println("response.getStatusLine `````````````````````` " +response.getStatusLine());
}
}
答案 0 :(得分:0)
问题不在您的代码中。我试过了,它工作正常。它位于您的控制台/ Eclipse / IntelliJIdea中,取决于您启动它的位置。 我已修改您的代码以写入文件:
String responseString = EntityUtils.toString(response.getEntity(), "big5");
response = demo.execute(httpPost);
//responseString = EntityUtils.toString(response.getEntity());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
FileOutputStream fos = new FileOutputStream("C:\\test\\Big5Test.html");
response.getEntity().writeTo(fos);
fos.close();
} else {
System.out.println("response.getStatusLine `````````````````````` " +response.getStatusLine());
}
当我在Firefox中打开文件时,一切都很好。请在您的系统上试用。