我是java的新手。我有一个URL,用户名,密码。我需要使用URL,UserName和Password发出PUT HTTP请求。 我必须使用HTTP Put请求将JSON文件作为有效负载发送到系统,该系统只能接受JSON。
我在StackOverFlow中搜索过,发现一些建议可以在没有用户名和密码的情况下向URL发出简单请求。但我们的网址需要通过身份验证才能提出请求。
我用来发出HTTP请求的代码
public static void main (String args[]) throws IOException
{
String userPassword = "";
String encoding = new String(Base64.encodeBase64(userPassword.getBytes()));
URL url = new URL(URL);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
httpCon.setRequestProperty("Authorization", "Basic "+encoding);
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
}
答案 0 :(得分:0)
使用排球库......轻松
RequestQueue queue = Volley.newRequestQueue(this);
String url = "<your url>";
JSONObject jsonrequest=new JSONObject();
jsonrequest.put("username",<username>);
jsonrequest.put("password",<password>);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, jsonrequest, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
//your code to handle when response came
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);