java发送带BasicAuth认证的httppost请求实例代码构造http header
private static final String URL = "url";
private static final String APP_KEY = "key";
private static final String SECRET_KEY = "secret";
/**
* 构造Basic Auth认证头信息
*
* @return
*/
private String getHeader() {
String auth = APP_KEY + ":" + SECRET_KEY;
byte[] encodedAuth = Bytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);
return authHeader;
}
⽅式⼀:
private void send(JPushObject pushObject) {
CloseableHttpClient client = ateDefault();
HttpPost post = new HttpPost(URL);
System.out.println("要发送的数据" + JSONString(pushObject));
StringEntity myEntity = new JSONString(pushObject), ContentType.APPLICATION_JSON); // 构造请求数据
post.addHeader("Authorization", getHeader());
post.setEntity(myEntity); // 设置请求体
String responseContent = null; // 响应内容
CloseableHttpResponse response = null;
try {
response = ute(post);
System.out.JSONString(response));
if (StatusLine().getStatusCode() == 200) {
HttpEntity entity = Entity();
responseContent = String(entity, "UTF-8");
}
if (response != null)
response.close();
if (client != null)
client.close();
System.out.println("responseContent:" + responseContent);
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
⽅式⼆:
引⽤到的jar: httpclient-4.5.jar; httpcore-4.4.1.jar; commons-logging-1.2.jar; common-codec-1.9.jar
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.hods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClientWithBasicAuth {
public static void main(String args[])  {
String host = "10.104.203.166";
int port = 8080;
String URI = "localhost/rest/channel/receipt";
// 创建HttpClientBuilder
httpClientBuilder httpClientBuilder = ate();
// 设置BasicAuth
mvc实例CredentialsProvider provider = new BasicCredentialsProvider();
/
/ Create the authentication scope
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// Create credential pair,在此处填写⽤户名和密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("root", "superuser");
// Inject the credentials
provider.setCredentials(scope, credentials);
// Set the default credentials provider
httpClientBuilder.setDefaultCredentialsProvider(provider);
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
String result = "";
HttpGet httpGet = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
httpGet = new HttpGet(""+host+URI);
try {
httpResponse = ute(httpGet);
entity = Entity();
if( entity != null ){
result = String(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 关闭连接
closeableHttpClient.close();
//
System.out.println(result);
}
}
⽅式三.
import java.io.IOException;
import net.sf.json.JSONObject;
import del.User;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.hods.HttpPost;
import org.ity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class Client {
@Test
public void HttpPostData() {
try {
HttpClient httpclient = new DefaultHttpClient();
String uri = "localhost:8080/springMVC/user/getUserByName";
HttpPost httppost = new HttpPost(uri);
//添加http头信息
httppost.addHeader("Authorization", "your token"); //认证token
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("User-Agent", "imgfornote");
JSONObject obj = new JSONObject();
obj.put("name", "cwh");
httppost.setEntity(new String()));
HttpResponse response;
response = ute(httppost);
//检验状态码,如果成功接收数据
int code = StatusLine().getStatusCode();
System.out.println(code+"code");
if (code == 200) {
String rev = Entity());//返回json格式: {"id": "","name": ""}
obj= JSONObject.fromObject(rev);
User user = (Bean(obj,User.class);
System.out.println("返回数据==="+String());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();              } catch (Exception e) {                  e.printStackTrace();              }
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。