繁体   English   中英

发出HTTPS请求时出现问题

[英]Trouble when making a HTTPS request

我有这个异步任务:

public class likeTheJoke extends AsyncTask<Void, Integer, Void>{        

    @Override
    protected Void doInBackground(Void... params) {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://site.com/android/jokes/updateLikes.php");

        try {
             // Add data
            String encodedUrl = URLEncoder.encode("Joke 7", "UTF-8"); // recently added after a comment suggestion
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("jokeName", encodedUrl));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }       
}

我正在尝试将参数传递给我的php脚本并更新数据库中的值。 使用上面的代码,我的链接应类似于: https://site.com/android/jokes/updateLikes.php?jokeName=Joke 7 : https://site.com/android/jokes/updateLikes.php?jokeName=Joke 7

问题是在请求之后,什么都没有发生。 我知道这是正常的,因为使用HTTPS ,但是即使这里有大约10个答案,我也确实找不到使请求正常工作的方法。 您能引导我并告诉我我所缺少的吗? 我知道它确实很小,但我无法发现它。

这是我的php代码(只是一个附加信息):

<?php
$jokeName = urldecode($_GET["jokeName"]); // urldecode added after a comment suggestion.

$con=mysqli_connect("localhost","user","pass","database");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"UPDATE JOKES SET likes = likes+1
WHERE jokeName='$jokeName'");

mysqli_close($con);
?>

附言:我已在发布的代码中更改了站点名称和数据库详细信息。

您应该使用“ URL编码”来确保目标字符串中的空白已正确转换。

您正在发送一个以jokeName=joke 7作为帖子正文(实体)的帖子。 但是在php方面,您尝试将其作为GET参数(URL参数)获取。 因此,笑话ID不会传递到PHP端。

一些在php端的简单登录应该可以揭示这一点。

添加jokeName=Joke 7作为url参数,或在php端使用$_POST['jokeName']

如果有人遇到相同的问题,这是我的解决方法:

    try{
                String encodedUrl = URLEncoder.encode("name with spaces", "UTF-8");
                URL url = new URL("https://site.com/android/dir/file.php?paramName="+encodedUrl);
                URLConnection urlConnection = url.openConnection();
                @SuppressWarnings("unused")
                InputStream in = urlConnection.getInputStream();
                }catch(Exception e){
                    e.printStackTrace();
                }
    }

在php中,您需要转义和解码url中的参数,例如:

$categoryParam= mysql_real_escape_string(urldecode($_GET["Param"]));

这样做可能不是最好的方法,但是它正在起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM