Несколько дней назад у меня были похожие проблемы.
Вы можете взглянуть на следующий код.
public class API {
// constants
private final String TAG = "API";
private final String API_URL_SECURE = "your url";
private final String API_URL = "your url";
private static API instance;
// data
private HttpClient client;
private ClientConnectionManager cm;
private HttpPost post;
private HttpContext httpContext;
private HttpParams params;
private API() {
params = new BasicHttpParams();
httpContext = new BasicHttpContext();
ConnManagerParams.setMaxTotalConnections(params, 300);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register( new Scheme("http", PlainSocketFactory.getSocketFactory(), 80) );
cm = new ThreadSafeClientConnManager(params, schemeRegistry);
client = new DefaultHttpClient(cm, params);
}
public static API getInstance(){
if(instance == null){
instance = new API();
return instance;
}
else
return instance;
}
private static String getCredentials(String userName, String password){
return Base64.encodeBytes((userName + ":" + password).getBytes());
}
private String makeRequest(String url, JSONObject json, String userName, String userPassword) {
try {
post = new HttpPost(url);
StringEntity en = new StringEntity(json.toString());
post.setEntity(en);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
if(userName != null && userPassword != null)
post.addHeader("Authorization","Basic "+ getCredentials(userName, userPassword));
HttpResponse responsePOST = client.execute(post, httpContext);
HttpEntity resEntity = responsePOST.getEntity();
return EntityUtils.toString(resEntity);
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public synchronized String login(String user_name, String user_password){
JSONObject json = new JSONObject();
JSONObject params = new JSONObject();
try {
json.put("method", "log_in_user");
params.put("user_name", user_name);
params.put("user_pass", user_password);
json.put("params", params);
String result = makeRequest(API_URL_SECURE, json, user_name, user_password);
return result;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
}