2016-05-22 69 views
0

我用我的本地主机制作了网站,它有一些值和按钮。 如果有人访问url(例如http://myhost/?status2=0),则值为变化。Android HttpUrlConnection不起作用

我想在Android的这个动作,所以我用HttpURLConnection,但它不起作用。

如果我在Android中使用Intent(ACTION_VIEW,Uri.parse("http..."))访问URL,它运行良好。

但我访问URL使用HttpURLConnection,它不起作用。我不知道什么是错的。请帮帮我。

这是Android应用程序中的代码。我已经检查清单。

try{ 
    URL url = new URL("http://myhost/?status2=0"); 

    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setUseCaches(false); 
    conn.setRequestMethod("POST"); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 

} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
+0

即时通讯不知道,但我想如果你想使用“HttpURLConnection”你的网址应该包含“www”。试试看并检查它是否有效? – pooyan

+0

您可以使用OkHttp第三方库。这是HttpURLConnection上许多人的首选。 – Vucko

回答

0

好吧,你可以使用RetrofitOkHttpHttpUrlConnection尝试这样的:

public void refreshToken(String url,String refresh,String cid,String csecret) throws IOException { 
     URL refreshUrl = new URL(url + "token"); 
     HttpURLConnection urlConnection = (HttpURLConnection) refreshUrl.openConnection(); 
     urlConnection.setDoInput(true); 
     urlConnection.setRequestMethod("POST"); 
     urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     urlConnection.setUseCaches(false); 
     String urlParameters = "grant_type=refresh_token&client_id=" + cid + "&client_secret=" + csecret + "&refresh_token=" + refresh; 
     // Send post request 
     urlConnection.setDoOutput(true); 
     DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); 
     wr.writeBytes(urlParameters); 
     wr.flush(); 
     wr.close(); 
     int responseCode = urlConnection.getResponseCode(); 
     //this is my Pojo class . I am converting response to Pojo with Gson 
     RefreshTokenResult refreshTokenResult = new RefreshTokenResult(); 
     if (responseCode == 200) { 

      BufferedReader in = new BufferedReader(
        new InputStreamReader(urlConnection.getInputStream())); 
      String inputLine; 
      StringBuffer response = new StringBuffer(); 

      while ((inputLine = in.readLine()) != null) { 
       response.append(inputLine); 
      } 
      in.close(); 
      // JSONObject obj=new JSONObject(response.toString()); 
      Gson gson = new Gson(); 
      refreshTokenResult = gson.fromJson(response.toString(), RefreshTokenResult.class); 
      //handle new token ... 
      mLoginPrefsEditor = mLoginPreferences.edit(); 
      mLoginPrefsEditor.commit(); 
      mLoginPrefsEditor.putString(mContext.getResources().getString(R.string.pref_accesstoken), "Bearer " + refreshTokenResult.getAccessToken()); 
      mLoginPrefsEditor.putString(mContext.getResources().getString(R.string.pref_refreshtoken), refreshTokenResult.getRefreshToken()); 
      mLoginPrefsEditor.commit(); 
     } 
} 

在我的其他请求我使用OkHttp支持Retrofit,但在刷新令牌 - 刷新令牌是一个关键过程对我来说 - 我正在使用HttpUrlConnection

当我在刷新标记方法中使用OkHttpRetrofit有时它不会正确。

我得到了这个:有时你需要使用基本的握手方法HttpUrlConnection

相关问题