日期:2014-05-20 浏览次数:20914 次
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class EncodedPostTest {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
BufferedReader bufReader = null;
String charset = "";
try {
HttpPost httppost = new HttpPost(
"http://localhost:8080/TestJEEProject/EncodingServlet");
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity().getContentEncoding() != null) {
charset = response.getEntity().getContentEncoding().getValue();
}else if(response.getEntity().getContentType() != null){
String contentType = response.getEntity().getContentType().getValue().toLowerCase().replaceAll("\\s*", "");
charset = contentType.substring(contentType.indexOf("charset=") + "charset=".length());
}else{
// //TODO: 使用默认字符编码
charset = "gbk";
}
System.out.println("Charset : " + charset);
bufReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
String strValue = bufReader.readLine();
while(strValue != null){
if(strValue.indexOf("编码") != -1){
System.out.println(strValue);
}
strValue = bufReader.readLine();
}
} else {
System.out.println("Unexpected failure: "
+ response.getStatusLine().toString());
}
} finally {
httpclient.getConnectionManager().shutdown();
if(bufReader != null){
bufReader.close();
}
}
}
}