java httpclient 编码_java – 使用httpclient进行URL编码

  • Post author:
  • Post category:java


如果您从URL urlObject = new URL(url)之类的字符串创建新的URL对象,然后执行urlObject.getQuery()和urlObject.getPath()将其拆分为右,将Query Params解析为List或Map或做某事并做一些事情:

编辑:我刚刚发现HttpClient库有一个URLEncodedUtils.parse()方法,您可以使用下面提供的代码轻松使用它.我会编辑它以适应,但是未经测试.

使用Apache HttpClient,它将类似于:

URI urlObject = new URI(url,”UTF-8″);

HttpClient httpclient = new DefaultHttpClient();

List formparams = URLEncodedUtils.parse(urlObject,”UTF-8″);

UrlEncodedFormEntity entity;

entity = new UrlEncodedFormEntity(formparams);

HttpPost httppost = new HttpPost(urlObject.getPath());

httppost.setEntity(entity);

httppost.addHeader(“Content-Type”,”application/x-www-form-urlencoded”);

HttpResponse response = httpclient.execute(httppost);

HttpEntity entity2 = response.getEntity();

使用Java URLConnection,它将类​​似于:

// Iterate over query params from urlObject.getQuery() like

while(en.hasMoreElements()){

String paramName = (String)en.nextElement(); // Iterator over yourListOfKeys

String paramValue = yourMapOfValues.get(paramName); // replace yourMapOfNameValues

str = str + “&” + paramName + “=” + URLEncoder.encode(paramValue);

}

try{

URL u = new URL(urlObject.getPath()); //here’s the url path from your urlObject

URLConnection uc = u.openConnection();

uc.setDoOutput(true);

uc.setRequestProperty(“Content-Type”,”application/x-www-form-urlencoded”);

PrintWriter pw = new PrintWriter(uc.getOutputStream());

pw.println(str);

pw.close();

BufferedReader in = new BufferedReader(new

InputStreamReader(uc.getInputStream()));

String res = in.readLine();

in.close();

// …

}



版权声明:本文为weixin_39718286原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。