pizzapablo
pizzapablo

Reputation: 107

HTTP Error 400 bad request python

from urllib.request import *
import urllib

def read_text():
    text = open("/home/pizzapablo666/Desktop/Test")
    contents_of_file = text.read()
    print(contents_of_file)
    text.close()
    check_profanity(contents_of_file)


def check_profanity(text_to_check):
    text_to_check = urllib.parse.quote_plus(text_to_check)
    connection = urlopen(
        "http://www.wdylike.appspot.com/?q=" + text_to_check)
    output = connection.read()
    print(output)
    connection.close()

read_text()

THis is updated version
HTTP 400 error bad request, what is the cause ? and how can I fix this error?

Upvotes: 2

Views: 6233

Answers (1)

Jordan Crowley
Jordan Crowley

Reputation: 26

I think it is because you are not encoding your string before appending it to your url.

For example, in python3 you should do the following to 'text_to_check' before appending it to your url:

text_to_check = urllib.parse.quote_plus(text_to_check)

Python2 would be something like this (urllib was broken into smaller components in python3):

text_to_check = urllib.quote_plus(text_to_check)

This means that, when appending a string with whitespace to your url it will appear as something like "Am+I+cursing%3F" instead of "Am I cursing?".

Full check_profanity() example:

def check_profanity(text_to_check):
    text_to_check = urllib.parse.quote_plus(text_to_check)
    connection = urlopen(
        "http://www.wdylike.appspot.com/?q=" + text_to_check)
    output = connection.read()
    print(output)
    connection.close()

Upvotes: 1

Related Questions