我正在尝试将 xml 格式的数据发送到其他服务器,这意味着使用 HttpClient 之类的 java 跨域。我检查了 stackoverflow 和 mkyong 中的其他帖子,但对我没有任何帮助。在 mkyong 这个帖子
[http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/][1] 正在工作,但我不知道如何在不使用参数的情况下发送数据。
请指导前进。感谢您的帮助。
编辑
我正在使用这段代码,它对我有用。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class workingCode {
public static void main(String[] args) throws ClientProtocolException, IOException {
try {
DefaultHttpClient client = new DefaultHttpClient();
String url = "https://selfsolve.apple.com/wcResults.do";
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", "Mozilla/5.0");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
urlParameters.add(new BasicNameValuePair("cn", ""));
urlParameters.add(new BasicNameValuePair("locale", ""));
urlParameters.add(new BasicNameValuePair("caller", ""));
urlParameters.add(new BasicNameValuePair("num", "12345"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode()+" Response StatusLine : " + response.getStatusLine());
InputStreamReader isp = new InputStreamReader(response.getEntity().getContent());
BufferedReader rd = new BufferedReader(isp);
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IllegalStateException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClientProtocolException cpe) {
// TODO Auto-generated catch block
cpe.printStackTrace();
}catch (IOException ie) {
// TODO Auto-generated catch block
ie.printStackTrace();
}
}
}
This is working but i need to send the data like this.
StringEntity entity = new StringEntity(data, HTTP.UTF_8);
entity.setContentType("application/x-www-form-urlencoded");
post.setEntity(entity);
当我通过将 url 更改为客户端 url 来执行此操作时,它失败了,但是当使用 javascript 执行此操作时,它会通过说“HTTP/1.1 401 Unauthorized”而失败。
谢谢你的帮忙